package lib

import (
	"context"
	"lib/db"
	"time"
)

func lockWithTimeout(key string, timeout time.Duration) (bool, error) {
	isLocked, err := db.GetRedisClient().SetNX(context.TODO(), key, "locked", timeout).Result()
	if err != nil {
		return false, err
	}
	return isLocked, nil
}

func unlock(key string) error {
	_, err := db.GetRedisClient().Del(context.TODO(), key).Result()
	return err
}

func RedisLock(key string) bool {
	timeout := 10 * time.Second
	isLocked, err := lockWithTimeout(key, timeout)
	if err != nil {
		return false
	}
	if isLocked {
		// 处理业务逻辑
		return true
	} else {
		return false
	}
	return true
}
func UnRedisLock(key string) bool {
	unlock(key)
	return true
}
